<template>
  <div class="jax-desc">
    <div class="jax-desc__header">
      <div class="jax-desc__title" v-if="title">{{ title }}</div>
      <!-- <div class="jax-desc-extra"></div> -->
    </div>
    <div class="jax-desc__body" :style="`--jax-desc-column:${column};`">
      <template v-if="data && faltJson">
        <jax-desc-item v-for="(item, index) in faltJson" :key="index" :label="item.label" :label-position="labelPosition">
          <template v-if="$slots[item.name]">
            <slot :name="item.name"></slot>
          </template>
          <template v-else>{{ item.value || data[item.name] }}</template>
        </jax-desc-item>
      </template>
      <slot></slot>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  data: Object,
  json: Array,
  title: String,
  labelWidth: { type: String, default: '56px' },
  labelPosition: String,
  column: { type: Number, default: 1 },
})

provide('jax-desc', {
  labelWidth: props.labelWidth,
  labelPosition: props.labelPosition,
})

const faltJson = computed(() => {
  return flatJsonStructure(props.json)
})

// 使用递归实现扁平化 JSON 结构
function flatJsonStructure(jsonArray) {
  let flatJson = []

  jsonArray.forEach((jsonEl) => {
    if (Array.isArray(jsonEl)) {
      const newflatJson = flatJsonStructure(jsonEl)
      flatJson = flatJson.concat(newflatJson)
    } else {
      flatJson.push(jsonEl)
    }
  })

  return flatJson
}
</script>

<style lang="scss" scoped>
.jax-desc {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

.jax-desc__header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.jax-desc__title {
  font-size: 16px;
  font-weight: 600;
}

.jax-desc__body {
  display: grid;
  grid-template-columns: repeat(var(--jax-desc-column), 1fr);
  grid-gap: 12px;
}
</style>
